<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webgl使用varying传值</title>
  <script src="lib/webgl-debug.js"></script>
  <script src="lib/webgl-utils.js"></script>
  <script src="lib/cuon-utils.js"></script>
  <script src="lib/cuon-matrix.js"></script>
</head>

<body onload="main()">
  <canvas id="canvas" width="400" height="490"></canvas>
</body>
<script>
  // 顶点着色器伪代码
  var vShder_source = `
  attribute vec4 position;
  // attribute float psize;
  attribute vec4 pcolor;
  varying vec4 fcolor;
void main(){
gl_Position =position; //设置坐标
// gl_PointSize =psize; //设置尺寸
fcolor = pcolor;
}
`
  //片元着色器伪代码
  var fShder_source = `
  precision mediump float;
  varying vec4 fcolor;
void main(){
gl_FragColor = fcolor; //设置颜色
}
`
  function main() {
    var canvas = document.getElementById('canvas');
    //  获取上下文对象
    var gl = getWebGLContext(canvas);
    //  初始化着色器
    if (!initShaders(gl, vShder_source, fShder_source)) {
      return;
    }
    var n = initVertexBuffer(gl);
    // 指定一个覆盖canvas的颜色
    gl.clearColor(0, 0, 0, 1.0);
    // 清除指定的缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLE_FAN, 0, n);
  }

  function initVertexBuffer(gl) {
    // 顶点数据
    var vertexDatas = new Float32Array([
      -0.5, 0.5, 40, 1, 0, 0,
      0.5, 0.5, 30, 0, 1, 0,
      0.5, -0.5, 20, 0, 0, 1,
      - 0.5, -0.5, 30, 1, 1, 1
    ]);
    // 创建缓冲区
    var vertexBuffer = gl.createBuffer();
    //绑定缓冲区
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertexDatas, gl.STATIC_DRAW);
    var bsize = vertexDatas.BYTES_PER_ELEMENT;
    var position = gl.getAttribLocation(gl.program, "position");
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, bsize * 6, 0);
    gl.enableVertexAttribArray(position);
    // var psize = gl.getAttribLocation(gl.program, "psize");
    // gl.vertexAttribPointer(psize, 1, gl.FLOAT, false, bsize * 6, bsize * 2);
    // gl.enableVertexAttribArray(psize);
    var pcolor = gl.getAttribLocation(gl.program, "pcolor");
    gl.vertexAttribPointer(pcolor, 3, gl.FLOAT, false, bsize * 6, bsize * 3);
    gl.enableVertexAttribArray(pcolor);
    return 4;
  }

</script>

</html>